/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EditorScreen.java
 *
 * Created on Aug 15, 2009, 4:08:47 PM
 */

package embuzzled.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author Satyajeet
 */
public class EditorScreen extends javax.swing.JFrame implements MouseListener{

     Boolean dragging;
    GCell[][] GameGrid;
    int g_rows, g_cols;
    GridIOManager giom;
    /** Creates new form EditorScreen */
    public EditorScreen() {
        initComponents();
        myInit();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        EditorGridPanel = new javax.swing.JPanel();
        Build = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        EditorGridlist = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        SaveGrid = new javax.swing.JButton();
        Load = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        EditorRows = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        EditorCols = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        EditorGridPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout EditorGridPanelLayout = new javax.swing.GroupLayout(EditorGridPanel);
        EditorGridPanel.setLayout(EditorGridPanelLayout);
        EditorGridPanelLayout.setHorizontalGroup(
            EditorGridPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 973, Short.MAX_VALUE)
        );
        EditorGridPanelLayout.setVerticalGroup(
            EditorGridPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 662, Short.MAX_VALUE)
        );

        Build.setText("Build new Grid");
        Build.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BuildActionPerformed(evt);
            }
        });

        EditorGridlist.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(EditorGridlist);

        jLabel3.setText("Grid List");

        SaveGrid.setText("Save Grid");
        SaveGrid.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveGridActionPerformed(evt);
            }
        });

        Load.setText("Load");
        Load.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoadActionPerformed(evt);
            }
        });

        jLabel4.setText("Rows");

        jLabel5.setText("Columns");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(EditorGridPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(66, 66, 66)
                                .addComponent(Load))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(EditorRows, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(EditorCols, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(Build)
                        .addGap(18, 18, 18)
                        .addComponent(SaveGrid)))
                .addContainerGap(94, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(EditorRows, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(EditorCols, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Build)
                    .addComponent(SaveGrid))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(127, 127, 127)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Load, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(EditorGridPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(49, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BuildActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BuildActionPerformed
        // TODO add your handling code here:
        if (EditorRows.getText().equalsIgnoreCase("")|| EditorCols.getText().equalsIgnoreCase(""))
        {
            return;
        }

        int rows = Integer.parseInt(EditorRows.getText());
        int cols = Integer.parseInt(EditorCols.getText());
        

        Grid localgrid = new Grid(rows, cols);

        gridBuilder(localgrid);


    }//GEN-LAST:event_BuildActionPerformed

    private void SaveGridActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveGridActionPerformed
        // TODO add your handling code here:
        // Use giom to (1) Convert grid to file and save
        // Provide it with the grid

        String gridname = JOptionPane.showInputDialog(null, "Enter Gridname");
        try {
            giom.saveGridtoFile(g_rows, g_cols, GameGrid, gridname);
        } catch (IOException ex) {
            Logger.getLogger(EditorScreen.class.getName()).log(Level.SEVERE, null, ex);
        }
        populateGridlist();
        



    }//GEN-LAST:event_SaveGridActionPerformed

    private void LoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadActionPerformed
        // TODO add your handling code here:
        // First get the filename and send it to readGridfromFile and it will return Grid object
        String filename = (String)EditorGridlist.getSelectedValue();
        if(filename == null)
        {
            return;
        }

        Grid localgrid = null;
        try {
            //System.out.println("You selected : " + filename);
             localgrid = giom.readGridfromFile(filename);
             gridBuilder(localgrid);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(EditorScreen.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(EditorScreen.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_LoadActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new EditorScreen().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Build;
    private javax.swing.JTextField EditorCols;
    private javax.swing.JPanel EditorGridPanel;
    private javax.swing.JList EditorGridlist;
    private javax.swing.JTextField EditorRows;
    private javax.swing.JButton Load;
    private javax.swing.JButton SaveGrid;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    private void myInit() {
        //throw new UnsupportedOperationException("Not yet implemented");
         dragging = false;
         giom = new GridIOManager();

         populateGridlist();
    }

    public void gridBuilder(Grid mygrid)
    {

//         int rows = Integer.parseInt(EditorRows.getText());
//        int cols = Integer.parseInt(EditorCols.getText());

        int rows = mygrid.rows;
        int cols = mygrid.cols;

        g_rows = rows;
        g_cols = cols;
        // The logical end of grid
        GameGrid = null;
        GameGrid = new GCell[rows][cols];

        EditorGridPanel.removeAll();

         EditorGridPanel.setLayout(new GridLayout(rows, cols));


        float gridheight = EditorGridPanel.getHeight();
        float gridwidth = EditorGridPanel.getWidth();

        // Now let us calculate size for block
        int blockheight = (int)(gridheight/rows);
        int blockwidth = (int)(gridwidth/cols);

        for (int loopr = 0; loopr< rows; loopr++)
        {
            for(int loopc = 0; loopc<cols; loopc++)
            {

                JPanel jp = new JPanel();
                Point pp = new Point(loopr, loopc);
                GCell gc = new GCell(jp, pp);
                gc.setPreferredSize(new Dimension(blockwidth ,blockheight));
                gc.setMaximumSize(new Dimension(blockwidth,blockheight));
                gc.setBorder(BorderFactory.createLineBorder(Color.GRAY));
                gc.addMouseListener(this);
                gc.GBool = mygrid.datagrid[loopr][loopc];
                if(gc.GBool == true)
                {
                    gc.setBackground(Color.DARK_GRAY);
                }
                gc.setToolTipText(loopr + "," + loopc);

                GameGrid[loopr][loopc] = gc;

               

                EditorGridPanel.add(gc);


            }
            //System.out.println("Done!");
             EditorGridPanel.repaint();
             EditorGridPanel.validate();
        }


    }


    public void populateGridlist()
    {

          EditorGridlist.removeAll();
         // Let us also populate the list with the gridnames
         
         ArrayList<String> gridnames = giom.getnames();
         EditorGridlist.setModel(new DefaultListModel());
         DefaultListModel dlm = (DefaultListModel) EditorGridlist.getModel();
         for(int loop=0;loop<gridnames.size();loop++)
         {
             dlm.addElement((Object)gridnames.get(loop));
         }


    }

     public void mouseClicked(MouseEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    public void mousePressed(MouseEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        handleClick(e);
        dragging = Boolean.TRUE;
    }

    public void mouseReleased(MouseEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        dragging = Boolean.FALSE;
    }

    public void mouseEntered(MouseEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        if(dragging == true)
        {
            handleClick(e);
        }
    }

    public void mouseExited(MouseEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    private void handleClick(MouseEvent e) {
        //throw new UnsupportedOperationException("Not yet implemented");
        GCell gc = (GCell)e.getSource();

        if(gc.GBool == false)
        {
            gc.setBackground(Color.DARK_GRAY);
            gc.GBool = true;
        }
        else
        {
            gc.setBackground(null);
            gc.GBool = false;
        }






    }

}
